package ch.zbw.sysventory.server.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ch.zbw.sysventory.server.model.ComputerScan;
import ch.zbw.sysventory.server.model.ComputerScanResult;
import ch.zbw.sysventory.server.model.Software;
import ch.zbw.sysventory.server.repository.SoftwareRepository;
import ch.zbw.sysventory.server.service.ComputerScanResultService;
import ch.zbw.sysventory.server.service.SoftwareService;

@Service
public class SoftwareServiceImpl implements SoftwareService {

	@Autowired
	private SoftwareRepository softwareRepository;

	@Autowired
	private ComputerScanResultService computerScanResultService;

	@Override
	public Software get(Long id) {
		return this.softwareRepository.findOne(id);
	}

	@Override
	public List<Software> list() {
		return this.softwareRepository.findAll();
	}

	@Override
	public Software save(Software software) {
		return this.softwareRepository.saveAndFlush(software);
	}

	@Override
	public Software update(Software software) {
		return this.softwareRepository.saveAndFlush(software);
	}

	@Override
	public Software createIfNotExists(String name, String version) {
		List<Software> softwareList = this.softwareRepository.findByNameAndVersion(name, version);
		if (softwareList.size() > 0) {
			return softwareList.get(0);
		} else {
			Software software = new Software();
			software.setName(name);
			software.setVersion(version);
			return this.save(software);
		}
	}

	@Override
	public List<Software> getAllSwoftwareForLatestScan(ComputerScan latestScan) {
		List<ComputerScanResult> scanResultList = this.computerScanResultService.listByComputerScan(latestScan);
		Map<String, Software> resultMap = new HashMap<String, Software>();
		Iterator<ComputerScanResult> scanResultIterator = scanResultList.iterator();
		while (scanResultIterator.hasNext()) {
			ComputerScanResult computerScanResult = scanResultIterator.next();
			List<Software> softwareList = computerScanResult.getSoftwareList();
			Iterator<Software> softwareIterator = softwareList.iterator();
			while (softwareIterator.hasNext()) {
				Software software = softwareIterator.next();
				resultMap.put(software.getName() + "#" + software.getVersion(), software);
			}
		}
		List<Software> resultList = new ArrayList<Software>(resultMap.values());
		Collections.sort(resultList, new Comparator<Software>() {
			@Override
			public int compare(Software software1, Software software2) {
				return software1.getName().compareTo(software2.getName());
			}
		});
		return resultList;
	}
}
